<template>
  <div class="">
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          v-model="name"
          name="name"
          label="姓名"
          placeholder="姓名"
          :rules="[{ required: true, message: '请填写姓名' }]"
        />
        <van-field
          v-model="grade"
          type="text"
          name="grade"
          label="班级"
          placeholder="班级"
          :rules="[{ required: true, message: '请填写班级' }]"
        />
        <van-field
          v-model="home"
          type="text"
          name="home"
          label="宿舍号"
          placeholder="宿舍号"
          :rules="[{ required: true, message: '请填写宿舍号' }]"
        />
        <van-field name="sex" label="性别">
          <template #input>
            <van-radio-group v-model="sex" direction="horizontal">
              <van-radio name="男">男</van-radio>
              <van-radio name="女">女</van-radio>
            </van-radio-group>
          </template>
        </van-field>
      </van-cell-group>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { ref, reactive, toRefs, computed } from "vue";
import { useStore } from "vuex";
import { useRouter, useRoute } from "vue-router";
export default {
  setup(props, ctx) {
    const store = useStore();
    const router = useRouter();
    const route = useRoute();

    const data = reactive({
      name: "",
      grade: "",
      home: "",
      sex: "",
    });
    const index = route.params.index;
    //拿到要编辑的数据的下标
    const item = computed(() => {
      return store.state.studentList[index];
    });
    //拿到要编辑的这一条数据

    data.name = item.value.name;
    data.grade = item.value.grade;
    data.sex = item.value.sex;
    data.home = item.value.home;
    // 数据回填 计算属性也要 加value

    const onSubmit = (val) => {
      console.log(val);
      store.commit("edit", { index: index, val: val });
      //把下标和修改过后的数据都传过去
      router.push("/");
    };
    return { ...toRefs(data), item, onSubmit };
  },
};
</script>

<style lang="scss"></style>
